package OuterGameParts;

import java.io.IOException;
import java.rmi.RemoteException;
import InnerGameParts.CannonBall;
import InnerGameParts.PirateShip;
import InnerGameParts.RemoteList;
import InnerGameParts.Wind;




public class GameServer implements Runnable {


	private static int CANNON_DAMGE = 1;

	private RemoteList<PirateShip> myShips;
	private RemoteList<CannonBall> myBalls;
	private RemoteList<Wind> myWind;

	public GameServer( RemoteList<PirateShip> myShips, RemoteList<CannonBall> myBalls , RemoteList<Wind>theWind ) throws RemoteException, IOException{

		this.myShips =  myShips;
		this.myWind = theWind;
		this.myBalls =  myBalls;

		myWind.add(new Wind());

	}


	public void run(){

		try {

			while (true){

				updateGame();
				getConnections();
				try {
					Thread.sleep(100L);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

			}

		} catch (RemoteException e) {
			e.printStackTrace();
		}


	}

	private void getConnections(){



	}

	private void updateGame() throws RemoteException {

		//Updates the wind movement
		Wind theWind = myWind.get(0);
		theWind.windUpdate();
		updateShips();
		updateBalls();



	}

	private void updateShips() throws RemoteException{

		//upates all the ships movements
		lookThroughShips :  for(int count = 0; count <  myShips.size(); count++){

			if (myShips.get(count).getRequests() == null){

				continue lookThroughShips;
			}

			Requests [] requests = myShips.get(count).getRequests();

			if(requests[0] != null){
				myShips.get(count).moveForward(myWind.get(0));
			}
			if(requests[1] == Requests.TURN_RIGHT){
				myShips.get(count).turnRight();
			}else if(requests[1] == Requests.TURN_LEFT){

				myShips.get(count).turnLeft();
			}

			if(requests[3] != null){
				
				
			}
			

			if(requests[3] != null){

				myBalls.add(myShips.get(count).shootLeft());

			}

			if(requests[4] != null){

				myBalls.add(myShips.get(count).shootRight());

			}

			myShips.get(count).updateAmmo();
			
		}

	}

	private  void updateBalls() throws RemoteException{

		CannonBall currentBall = myBalls.getFirst();


		//goes though all the cannonballs in the list
		while(currentBall != null){


			//looks to see if if I should delete it
			if( currentBall.shouldDelete()){

				myBalls.remove(currentBall);

			} else{

				currentBall.move();

				//looks to see if that ball collides with any other ball
				for( int count = 0; count < myShips.size(); count++){

					///*
					  if( myShips.get(count).collide(currentBall)){
					 

						myShips.get(count).hit(CANNON_DAMGE);
						myBalls.remove(currentBall);

					}
					//*/

				}
			}

			currentBall = myBalls.next(currentBall);

		}

	}

	public void CloseServer(){

		//TODO put in closing down theserver hack.


	}




}
